package com.taobao.diamond.config;

import com.taobao.diamond.manager.DiamondManager;
import com.taobao.diamond.manager.ManagerListener;
import com.taobao.diamond.manager.impl.DefaultDiamondManager;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;

/**
 * <p>@description: 对DiamondManger二次封装,提供统一的对外接口</p>
 *
 * @author yangshuang
 * @version 1.0
 * @date 2018/10/17 下午11:23
 */
public class DmallDiamondManager {

    private Map<String, DiamondManager> managerMap = new ConcurrentHashMap<>();


    private String diamondServer;


    private Integer port;

    public DiamondManager getDiamondManager(String dataId, String groupId) {

        //假装有一个key
        //加重入锁
        //根据key读取
        String key = "";
        DiamondManager diamondManager = managerMap.get(key);

        if (diamondManager == null) {
            //指定的dataId和groupId没有获取到DiamondMananger则创建一个新的客户端
            return createDiamondManager(dataId, groupId);
        }
        return diamondManager;

    }


    /**
     * 创建一个新的DiamondManager
     *
     * @param dataId
     * @param groupId
     * @return
     */
    private DiamondManager createDiamondManager(String dataId, String groupId) {

        DiamondManager manager = new DefaultDiamondManager(groupId, dataId,
                new ManagerListener() {
                    public void receiveConfigInfo(String configInfo) {
                        System.out.println("changed config: " + configInfo);
                    }

                    public Executor getExecutor() {
                        return null;
                    }
                }, diamondServer);
        //设置diamond-server服务的端口
        manager.getDiamondConfigure().setPort(port);

        managerMap.put("key", manager);
        return manager;
    }


    /**
     * 初始化方法
     *
     * @param diamondServer
     * @param port
     */
    public void init(String diamondServer, Integer port) {

        this.diamondServer = diamondServer;
        this.port = port;
    }

    /**
     * 销毁
     */
    public void close() {

        for (Map.Entry<String, DiamondManager> managerEntry : managerMap.entrySet()) {
            DiamondManager diamondManager = managerEntry.getValue();
            diamondManager.close();

        }
        managerMap.clear();


    }


}
